<?php

namespace App\Admin\Controllers;

use App\Http\Controllers\Controller;
use App\Models\PickupPointApplication;
use App\Models\Store;
use Dcat\Admin\Layout\Content;
use Illuminate\Http\Request;

class PickupApplicationController extends Controller
{
    /**
     * 申请列表
     *
     * @param Content $content
     * @param Request $request
     * @return Content
     */
    public function index(Content $content, Request $request)
    {
        return $content
            ->title('申请列表')
            ->description('管理自提点申请')
            ->body($this->renderApplicationList($request));
    }

    /**
     * 申请详情
     *
     * @param Content $content
     * @param int $id
     * @return Content|string
     */
    public function show(Content $content, $id)
    {
        // 如果是Ajax请求，只返回详情内容
        if (request()->ajax()) {
            return $this->renderApplicationDetail($id);
        }
        
        return $content
            ->title('申请详情')
            ->description('查看申请详细信息')
            ->body($this->renderApplicationDetail($id));
    }

    /**
     * 审核申请
     *
     * @param Content $content
     * @param int $id
     * @return Content
     */
    public function review(Content $content, $id)
    {
        return $content
            ->title('审核申请')
            ->description('审核自提点申请')
            ->body($this->renderApplicationReview($id));
    }

    /**
     * 渲染申请列表
     *
     * @param Request $request
     * @return string
     */
    protected function renderApplicationList(Request $request)
    {
        // 构建查询
        $query = PickupPointApplication::with('store')
            ->orderBy('created_at', 'desc');

        // 搜索条件
        if ($request->filled('applicant_id')) {
            $query->where('id', $request->applicant_id);
        }

        if ($request->filled('member_info')) {
            $memberInfo = $request->member_info;
            $query->whereHas('store', function ($q) use ($memberInfo) {
                $q->where('store_name', 'like', "%{$memberInfo}%")
                  ->orWhere('username', 'like', "%{$memberInfo}%")
                  ->orWhere('mobile', 'like', "%{$memberInfo}%");
            });
        }

        if ($request->filled('status')) {
            $query->where('status', $request->status);
        }

        // 分页
        $applications = $query->with(['store.member'])->paginate(10);

        // 转换数据格式以适配视图
        $formattedApplications = $applications->map(function ($app) {
            return [
                'id' => $app->id,
                'pickup_id' => $app->id,
                'pickup_name' => $app->store->store_name ?? '未知门店',
                'applicant' => [
                    'name' => $app->store->member->nickname ?? '未知联系人',
                    'id' => $app->store->member->uid ?? '未知ID',
                    'avatar' => $app->store->member->avatar ?? $this->generateAvatar('未知')
                ],
                'phone' => $app->store->mobile ?? '未知电话',
                'status' => $app->status_label,
                'status_class' => $this->getStatusClass($app->status),
                'submitted_at' => $app->submitted_at ? $app->submitted_at->format('Y-m-d H:i') : '未提交',
                'reviewed_at' => $app->reviewed_at ? $app->reviewed_at->format('Y-m-d H:i') : null,
                'reason' => $app->reason
            ];
        });

        return view('admin.pickup.applications', [
            'applications' => $formattedApplications,
            'pagination' => $applications,
            'request' => $request
        ]);
    }

    /**
     * 渲染申请详情
     *
     * @param int $id
     * @return string
     */
    protected function renderApplicationDetail($id)
    {
        try {
            $application = PickupPointApplication::with(['store.member', 'reviewer'])->findOrFail($id);

            // 安全获取门店信息
            $store = $application->store;
            $member = $store ? $store->member : null;

            // 获取审核人信息
            $reviewer = $application->reviewer;
            $reviewerName = $reviewer ? ($reviewer->username ?: $reviewer->name ?: '管理员') : '-';

            $formattedApplication = [
                'id' => $application->id,
                'store_id' => $application->store_id,
                'store_name' => $store ? ($store->store_name ?: '未知门店') : '未知门店',
                'store_contact' => $member ? ($member->nickname ?: '未知联系人') : '未知联系人',
                'store_phone' => $store ? ($store->mobile ?: '未知电话') : '未知电话',
                'store_address' => $store ? ($store->address ?: '未知地址') : '未知地址',
                'business_license' => $store ? $this->formatImageUrl($store->aptitude_imgs) : '未提供',
                'status' => $application->status,
                'status_label' => $application->status_label,
                'status_class' => $this->getStatusClass($application->status),
                'reason' => $application->reason,
                'reviewer_name' => $reviewerName,
                'submitted_at' => $application->submitted_at ? $application->submitted_at->format('Y-m-d H:i:s') : '未提交',
                'reviewed_at' => $application->reviewed_at ? $application->reviewed_at->format('Y-m-d H:i:s') : '未审核',
                'created_at' => $application->created_at->format('Y-m-d H:i:s'),
                'updated_at' => $application->updated_at->format('Y-m-d H:i:s'),
            ];

            return view('admin.pickup.application_detail', compact('formattedApplication'));
        } catch (\Exception $e) {
            // 记录错误日志
            \Log::error('获取申请详情失败: ' . $e->getMessage(), [
                'id' => $id,
                'trace' => $e->getTraceAsString()
            ]);

            // 如果没有找到记录，提供测试数据
            $formattedApplication = [
                'id' => $id,
                'store_id' => 1,
                'store_name' => '测试门店',
                'store_contact' => '测试联系人',
                'store_phone' => '13800138000',
                'store_address' => '测试地址',
                'business_license' => 'https://via.placeholder.com/300x200/4CAF50/FFFFFF?text=营业执照示例',
                'status' => 'pending',
                'status_label' => '待审核',
                'status_class' => 'badge-warning',
                'reason' => null,
                'reviewer_name' => '-',
                'submitted_at' => now()->format('Y-m-d H:i:s'),
                'reviewed_at' => '未审核',
                'created_at' => now()->format('Y-m-d H:i:s'),
                'updated_at' => now()->format('Y-m-d H:i:s'),
            ];

            return view('admin.pickup.application_detail', compact('formattedApplication'));
        }
    }

    /**
     * 渲染申请审核
     *
     * @param int $id
     * @return string
     */
    protected function renderApplicationReview($id)
    {
        $application = [
            'id' => $id,
            'applicant_name' => '李明',
            'business_name' => '便民超市',
            'phone' => '13900139001',
            'address' => '北京市海淀区中关村大街1号',
            'status' => '待审核'
        ];

        return view('admin.pickup.review', compact('application'));
    }

    /**
     * 审核通过
     *
     * @param Request $request
     * @param int $id
     * @return \Illuminate\Http\JsonResponse
     */
    public function approve(Request $request, $id)
    {
        try {
            $application = PickupPointApplication::findOrFail($id);
            
            $application->update([
                'status' => PickupPointApplication::STATUS_APPROVED,
                'reason' => $request->input('reason', '审核通过'),
                'reviewer_id' => auth()->id() ?? 1, // 当前审核人ID
                'reviewed_at' => now()
            ]);

            return response()->json([
                'status' => 'success',
                'message' => '审核通过成功'
            ]);
        } catch (\Exception $e) {
            return response()->json([
                'status' => 'error',
                'message' => '审核失败：' . $e->getMessage()
            ], 500);
        }
    }

    /**
     * 审核拒绝
     *
     * @param Request $request
     * @param int $id
     * @return \Illuminate\Http\JsonResponse
     */
    public function reject(Request $request, $id)
    {
        $request->validate([
            'reason' => 'required|string|max:500'
        ], [
            'reason.required' => '请输入拒绝原因'
        ]);

        try {
            $application = PickupPointApplication::findOrFail($id);
            
            $application->update([
                'status' => PickupPointApplication::STATUS_REJECTED,
                'reason' => $request->reason,
                'reviewer_id' => auth()->id() ?? 1, // 当前审核人ID
                'reviewed_at' => now()
            ]);

            return response()->json([
                'status' => 'success',
                'message' => '审核拒绝成功'
            ]);
        } catch (\Exception $e) {
            return response()->json([
                'status' => 'error',
                'message' => '审核失败：' . $e->getMessage()
            ], 500);
        }
    }

    /**
     * 生成头像
     *
     * @param string $name
     * @return string
     */
    private function generateAvatar($name)
    {
        $colors = ['#FF6B6B', '#4ECDC4', '#45B7D1', '#96CEB4', '#FFEAA7', '#DDA0DD', '#98D8C8', '#F7DC6F'];
        $color = $colors[strlen($name) % count($colors)];
        $initial = mb_substr($name, 0, 1);
        
        return "data:image/svg+xml;base64," . base64_encode(
            '<svg width="32" height="32" viewBox="0 0 32 32" fill="none" xmlns="http://www.w3.org/2000/svg">
                <circle cx="16" cy="16" r="16" fill="' . $color . '"/>
                <text x="16" y="20" text-anchor="middle" fill="#FFF" font-size="14px" font-weight="bold">' . $initial . '</text>
            </svg>'
        );
    }

    /**
     * 获取状态样式类
     *
     * @param string $status
     * @return string
     */
    private function getStatusClass($status)
    {
        switch ($status) {
            case PickupPointApplication::STATUS_PENDING:
                return 'badge-warning';
            case PickupPointApplication::STATUS_APPROVED:
                return 'badge-success';
            case PickupPointApplication::STATUS_REJECTED:
                return 'badge-danger';
            default:
                return 'badge-secondary';
        }
    }

    /**
     * 格式化图片URL
     *
     * @param string|array|null $imageUrl
     * @return string|array
     */
    private function formatImageUrl($imageUrl)
    {
        if (empty($imageUrl)) {
            return '未提供';
        }

        // 如果是数组，处理第一个图片或所有图片
        if (is_array($imageUrl)) {
            $images = [];
            foreach ($imageUrl as $url) {
                if (!empty($url)) {
                    $images[] = $this->processSingleImageUrl($url);
                }
            }
            return !empty($images) ? implode(',', $images) : '未提供';
        }

        // 处理单个图片
        return $this->processSingleImageUrl($imageUrl);
    }

    /**
     * 处理单个图片URL
     *
     * @param string $imageUrl
     * @return string
     */
    private function processSingleImageUrl($imageUrl)
    {
        if (empty($imageUrl)) {
            return '';
        }

        // 如果已经是完整的URL，直接返回
        if (filter_var($imageUrl, FILTER_VALIDATE_URL)) {
            return $imageUrl;
        }

        // 如果是相对路径，添加域名前缀
        if (strpos($imageUrl, '/') === 0) {
            return request()->getSchemeAndHttpHost() . $imageUrl;
        }

        // 如果是文件名，假设存储在public目录下
        return request()->getSchemeAndHttpHost() . '/storage/' . $imageUrl;
    }
}